<template>
	<view class="container">
		<swiper class="swiperBox">
			<swiper-item>
				<image :src="menu[0].thumb[0].url" class="swiperItem"></image>
			</swiper-item>
		</swiper>
		<view class="topMenuBox">
			<view class="topMenuItem" :class="topMenuIndex==index?'topMenuItemActive':''"
				v-for="(item,index) in parentMenu" :key="index" @click="changeTopMenu(index)">
				{{item.name}}
				<view class="triangle" v-if="topMenuIndex==index">
				</view>
			</view>
		</view>
		<view class="leftMenuBox">
			<view class="leftMenuItem" :class="leftMenuIndex==index?'leftMenuItemActive':''"
				v-for="(item,index) in childMenu" :key="index" @click="changeChild(index)">
				{{item.name}}
				<view class="leftLine" v-if="leftMenuIndex==index">
				</view>
			</view>
		</view>
		<scroll-view class="rightMenuBox" :scroll-top="scrollTop" scroll-y="true" @scrolltolower="getMore()">
			<view class="canshiInfo">
				<view class="canshiItem" v-for="(item,index) in data" :key="index"
					@click.stop="$navto.navto('/pages/juanjiahui_dinner_info/juanjiahui_dinner_info',{id:item.id})">
					<image :src="item.cover" class="canshiPoster"></image>
					<text class="canshiName ellipsis">{{item.name}}</text>
					<view class="canshiPriceBox">
						<text class="sellPrice">￥{{item.price}}</text>
						<!-- <text class="linePrice">￥{{item.old_price}}</text> -->
					</view>
					<view class="countNumBox">
						<view class="reduce" @click.stop="del(item.id)">
							-
						</view>
						<input type="text" disabled="true" class="countNum" :value="item.num" />
						<view class="add" @click.stop="add(item.id,1,item.cat_id)">
							+
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="cartBox">
			<text class="totalPrice">￥{{cartTotal.dishes_price|| 0}}</text>
			<view class="submit" @click="submit">
				提交订单
			</view>
			<view class="cart" @click="showCart()">
				<image :src="baseUrl+'/img/juanjiahui/cart.png'" class="cartImg"></image>
				<view class="cartNum">{{cartTotal.dishes_num || 0 }}</view>
			</view>
		</view>
		<view class="cartContainer" v-if="isCart">
			<view class="cartInner">
				<image :src="baseUrl+'/img/juanjiahui/close.png'" class="close" @click="showCart"></image>
				<view class="cartLabel">
					购物车
				</view>
				<view class="selectedBox">
					<text class="selectedLabe">已选择商品（{{cartTotal.dishes_num || 0 }}件）</text>
					<view class="deletedRight" @click="clear()">
						<image :src="baseUrl+'/img/juanjiahui/delete.png'" class="deletedIcon"></image>
						<text class="deleteText">清空购物车</text>
					</view>
				</view>
				<view class="cartItemBox">
					<view class="cartItem" v-for="(item,index) in cartTotal.dishes" :key="index">
						<image :src="item.cover" class="cartPoster"></image>
						<text class="cartName">{{item.name}}</text>
						<view class="cartPriceBox">
							<text class="sellPrice">￥{{item.price}}</text>
							<text class="linePrice">￥{{item.old_price}}</text>
						</view>
						<view class="countNumBox">
							<view class="reduce" @click.stop="del(item.dishes_id)">
								-
							</view>
							<input type="text" disabled="true" class="countNum" :value="item.num" />
							<view class="add" @click.stop="add(item.dishes_id,1,item.cat_id)">
								+
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				baseUrl: this.$baseUrl,
				num: 1,
				accordionVal: '',
				isCart: false,
				topMenuIndex: 0,
				leftMenuIndex: 0,
				parentMenu: '',
				childMenu: '',
				childMenuIndex: 0,
				data: '',
				data1: '',
				data2: '', //咖啡吧
				data3: '', //鸡尾酒
				data4: '', //下午茶
				open: false,
				cartTotal: '', //购物车商品
				typeArr: [], //分类商品
				menu: '',
				page: 1,
				hasMore: true, // 默认有更多数据
				scrollTop: 0,
			}
		},
		onShow() { //查询购物车
			if (this.token) {
				this.getCart();
			} else {
				this.$store.watch(
					(state) => state.token,
					(newToken) => {
						if (newToken) {
							this.getCart();
						}
					}
				);
			}
		},
		onLoad() {
			this.$request.get('sub_cat_index?parent_id=0').then(res => {
				this.menu = res.data.data;
			})
			// 主目录
			this.$request.get('sub_cat_index?parent_id=1').then(res => {
				this.parentMenu = res.data.data;
				// 餐食的子目录
				this.$request.get(`sub_cat_index?parent_id=${this.parentMenu[0].id}`).then(res => {
					this.childMenu = res.data.data;
					this.$request.get(`dishes_list?cat_id=${this.childMenu[0].id}`).then(res => {
						this.data = res.data.data.map(item => ({
							...item,
							num: 0
						}));
					});
				})
			})
		},
		methods: {
			getMore() {
				if (this.hasMore) {
					this.page++;
					this.getData(this.topMenuIndex);
				}
			},
			changeTopMenu(index) {
				this.data=[];
				this.leftMenuIndex=0;
				this.scrollTop = 0; // 使用 scroll-top 方式
				this.hasMore = true;
				this.topMenuIndex = index;
				this.page = 1;
				this.getData(this.topMenuIndex);
			},
			getData(index) {
				this.$request.get(`sub_cat_index?parent_id=${this.parentMenu[index].id}`).then(res => {
					this.childMenu = res.data.data;
					if (this.childMenu.length != 0) {
						this.$request.get(`dishes_list?cat_id=${this.childMenu[index].id}&page=${this.page}`).then(
							res => {
								if(res.data.data.length==0){
									this.hasMore = false; // 没有更多数据了
									this.$toast('没有更多数据了');
									return;
								}
								// 如果是第一页，直接覆盖 data
								if (this.page === 1) {
									this.data = res.data.data.map(item => ({
										...item,
										num: 0
									}));
								} else {
									// 如果不是第一页，追加新数据到 data
									const newData = res.data.data.map(item => ({
										...item,
										num: 0
									}));
									this.data = [...this.data, ...newData];
								}
							});
					} else {
						this.childMenu.push({
							name: '默认分类'
						});
						this.$request.get(`dishes_list?cat_id=${this.parentMenu[index].id}&page=${this.page}`)
							.then(res => {
								if(res.data.data.length==0){
									this.hasMore = false; // 没有更多数据了
									this.$toast('没有更多数据了');
									return;
								}
								// 如果是第一页，直接覆盖 data
								if (this.page === 1) {
									this.data = res.data.data.map(item => ({
										...item,
										num: 0
									}));
								} else {
									// 如果不是第一页，追加新数据到 data
									const newData = res.data.data.map(item => ({
										...item,
										num: 0
									}));
									this.data = [...this.data, ...newData];
								}
							});
					}
				});
			},
			submit() {
				if (this.cartTotal.dishes <= 0) {
					return this.$toast('请先添加商品');
				}
				this.$store.commit('setTempData', this.$data);
				this.$navto.navto("/pages/juanjiahui_dinner_submit/juanjiahui_dinner_submit")
			},
			changeChild(index) {
				this.childMenuIndex = index;
				this.leftMenuIndex = index;
				// 查询菜品
				this.$request.get(`dishes_list?cat_id=${this.childMenu[this.childMenuIndex].id}`).then(res => {
					this.data = res.data.data;
				})
			},
			info() {
				console.log("跳转详情")
			},
			clear() { //清空购物车
				if (this.cartTotal.dishes.length <= 0) {
					return this.$toast('购物车暂无商品');
				}
				uni.showModal({
					title: '提示',
					content: '是否确认清空购物车',
					success: (res) => {
						if (res.confirm) {
							this.$request.get(`user_del_cart`).then(res => {
								if (res.data.code == 10000) { // 更新购物车
									this.getCart();
									this.$toast('清除成功');
								} else {
									this.$toast('清除失败');
								}
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			del(id) {
			    // 1. 检查购物车中的商品是否存在
			    const cartItemIndex = this.cartTotal.dishes.findIndex(item => item.dishes_id === id);
			    if (cartItemIndex === -1) return; // 商品不在购物车中
			
			    const cartItem = this.cartTotal.dishes[cartItemIndex];
			    
			    // 2. 如果当前数量 <= 0，直接返回
			    if (cartItem.num <= 0) return;
			
			    // 3. 减少数量
			    cartItem.num -= 1;
			    this.cartTotal.dishes_price -= cartItem.price;
			    this.cartTotal.dishes_num -= 1;
			
			    // 4. 如果数量减到 0，从购物车中移除该商品
			    if (cartItem.num <= 0) {
			        this.cartTotal.dishes.splice(cartItemIndex, 1);
			    }
			
			    // 5. 更新当前分类的商品数据（如果存在）
			    const targetItem = this.data.find(item => item.id === id);
			    if (targetItem && targetItem.num > 0) {
			        targetItem.num -= 1;
			    }
			
			    // 6. 调用 API 更新服务器数据
			    this.$request.get(`del_cart?id=${id}`).then(res => {
			        if (res.data.code == 10000) {
			            this.$toast('删除成功');
			        } else {
			            this.$toast('删除失败');
			            // 回滚本地修改
			            if (cartItem.num === 0) {
			                // 如果之前删除了，重新加回来
			                this.cartTotal.dishes.splice(cartItemIndex, 0, { ...cartItem, num: 0 });
			            } else {
			                cartItem.num += 1;
			            }
			            this.cartTotal.dishes_price += cartItem.price;
			            this.cartTotal.dishes_num += 1;
			            if (targetItem) {
			                targetItem.num += 1;
			            }
			        }
			    });
			},
			add(dishes_id, num, cat_id) {
				const targetItem = this.data.find(item => item.id === dishes_id);
				if (targetItem) {
					targetItem.num += num;
				}
				this.$request.post(`add_cart`, {
					dishes_id: dishes_id,
					num: num,
					cat_id: cat_id
				}).then(res => {
					if (res.data.code == 10000) {
						this.getCart(); // 更新购物车
					} else {
						this.$toast('添加失败');
					}
				});
			},
			findItemById(dishes_id) {
				// 在 data1, data2, data3, data4 中查找对应的 item
				const allData = [...this.data1, ...this.data2, ...this.data3, ...this.data4];
				return allData.find(item => item.id === dishes_id);
			},
			change(e) {
				console.log(e);
			},
			showCart() {
				this.isCart = !this.isCart;
			},
			getCart() {
				this.$request.get(`user_cart_list`).then(res => {
					this.cartTotal = res.data.data;
					//分类商品
					let groupedDishes = this.cartTotal.dishes.reduce((acc, dish) => {
						let group = acc.find(g => g.cat_id === dish.cat_id);
						if (!group) {
							group = {
								cat_id: dish.cat_id,
								items: []
							};
							acc.push(group);
						}
						group.items.push(dish);
						return acc;
					}, []);

					this.typeArr = groupedDishes;

				}).catch(error => {
					console.error("获取购物车数据失败:", error);
				});
			}
		},
		computed: {
			...mapState(['token']),
		},
	}
</script>
<style lang="scss" scoped>
	.cartContainer {
		position: fixed;
		bottom: 0;
		z-index: 2;
		width: 100%;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.6);

		.cartInner {
			width: 100%;
			position: fixed;
			bottom: 0%;
			z-index: 2;
			background-color: #ffffff;
			padding: 40rpx 40rpx 150rpx 40rpx;
			box-sizing: border-box;
			display: flex;
			// align-items: center;
			flex-direction: column;

			.close {
				position: absolute;
				right: 6%;
				top: 4vw;
				width: 60rpx;
				height: 60rpx;
			}

			.cartItemBox {
				position: relative;
				width: 670rpx;
				max-height: 60vh;
				overflow-y: scroll;
				// background-color: red;

				.cartItem {
					position: relative;
					width: 670rpx;
					height: 140rpx;
					margin-bottom: 45rpx;

					.countNumBox {
						display: flex;
						align-items: center;
						position: absolute;
						top: 50%;
						transform: translateY(-50%);
						right: 30rpx;

						.add {
							display: flex;
							justify-content: center;
							height: 40rpx;
							line-height: 40rpx;
							font-size: 40rpx;
							width: 40rpx;
							border-radius: 50%;
							border: 1rpx solid #121212;
						}

						.reduce {
							display: flex;
							justify-content: center;
							height: 40rpx;
							line-height: 40rpx;
							font-size: 40rpx;
							width: 40rpx;
							border-radius: 50%;
							border: 1rpx solid #121212;
						}

						.countNum {
							width: 60rpx;
							text-align: center;
							font-size: 30rpx;
						}
					}

					.cartPriceBox {
						position: absolute;
						top: 85rpx;
						left: 240rpx;
						display: flex;
						align-items: center;

						.linePrice {
							color: #8e8e8e;
							font-weight: 500;
							font-size: 18rpx;
							margin-left: 20rpx;
							text-decoration: line-through;
						}

						.sellPrice {
							color: #121212;
							font-weight: 700;
							font-size: 22rpx;
						}
					}

					.cartName {
						position: absolute;
						font-weight: 700;
						font-size: 26rpx;
						color: #121212;
						top: 20rpx;
						left: 240rpx;
					}

					.cartPoster {
						width: 200rpx;
						height: 140rpx;
					}
				}
			}

			.selectedBox {
				display: flex;
				justify-content: space-between;
				margin-bottom: 60rpx;

				.deletedRight {
					display: flex;
					align-items: center;

					.deleteText {
						font-weight: 500;
						font-size: 20rpx;
						color: #121212;
						margin-left: 15rpx;
					}

					.deletedIcon {
						width: 26rpx;
						height: 24rpx;
					}
				}

				.selectedLabe {
					font-weight: 500;
					font-size: 24rpx;
					color: #121212;
				}
			}

			.cartLabel {
				font-weight: 700;
				font-size: 30rpx;
				color: #121212;
				padding-bottom: 35rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-bottom: 1rpx solid #000000;
				width: 100%;
				margin-bottom: 50rpx;
			}
		}
	}

	.content {
		width: 670rpx;
		padding-top: 50rpx;
		margin-left: 40rpx;
		border-top: 1rpx solid #000000;



		.menuInnerBox {
			width: 510rpx;
			margin-left: 80rpx;
			display: flex;
			justify-content: space-between;
			// align-items: center;
			margin-bottom: 50rpx;

			.left {
				display: flex;
				flex-direction: column;
				align-items: center;

				.menuInnerText {
					font-weight: 500;
					font-size: 26rpx;
					color: #121212;
				}

				.dot {
					width: 13rpx;
					height: 13rpx;
					border: 1rpx solid #121212;
					border-radius: 50%;
					margin-top: 20rpx;
				}
			}

			.line {
				width: 30rpx;
				height: 0;
				border-top: 1rpx dotted #717171;
				margin-top: 18rpx;
			}

			.menuInnerActive {
				font-weight: 700;
			}
		}
	}

	.cartBox {
		position: fixed;
		z-index: 3;
		bottom: 0;
		width: 100%;
		height: 130rpx;
		background-color: #ffffff;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		padding-left: 40rpx;
		padding-right: 40rpx;
		justify-content: space-between;
		padding-bottom: 20rpx;
		border-top: 1rpx solid #f0f0f0;

		.cart {
			position: absolute;
			left: 45rpx;
			top: -45rpx;

			.cartNum {
				position: absolute;
				top: -5rpx;
				right: -10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 35rpx;
				line-height: 35rpx;
				background-color: #FF7B6C;
				border-radius: 50%;
				font-size: 16rpx;
				color: #fff;
				box-sizing: border-box;
			}

			.cartImg {
				width: 80rpx;
				height: 80rpx;
			}
		}

		.totalPrice {
			color: #121212;
			font-weight: 700;
			font-size: 34rpx;
			letter-spacing: 2rpx;
		}

		.submit {
			width: 480rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background: #121212;
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: 700;
			font-size: 28rpx;
			color: #FFFFFF;
			letter-spacing: 5rpx;
		}
	}

	.bottomImg {
		width: 100%;
		height: 35vh;
	}


	::v-deep .uni-collapse-item__title-box {
		background-color: transparent;
	}

	::v-deep .uni-collapse-item__title {
		// background-color: #000000;
	}

	// ::v-deep .is-open >.uni-collapse-item__title-box {
	// 	background-color: #FFFFFF !important;
	// }
	::v-deep .uni-collapse-item__title.uni-collapse-item-border {
		border: none;
		// border-top: 1px solid #717171;
		// border-radius: 10rpx 10rpx 0 0;
	}

	::v-deep .uni-collapse-item {
		// border-radius: 100rpx;
		border-radius: 20rpx 20rpx 0 0;
		// height: 110rpx;
		background-color: #000000;
		margin-top: -12rpx;
		border-top: 1px solid #717171;
	}

	::v-deep .uni-collapse-item__title-text {
		text-align: center;
		font-size: 30rpx;
		height: 100%;
		width: 100%;
		font-weight: 600;
	}

	::v-deep .uni-collapse-item__title-arrow {
		display: none;
	}

	::v-deep .uni-collapse-item__title-box {
		height: 110rpx !important;
		// background-color: #121212 !important;
		color: #ffffff;
		padding: 0;
	}

	.menuBox {
		position: relative;
		width: 100%;
	}

	.rightMenuBox {
		width: 590rpx;
		height: 65vh;
		padding: 45rpx;
		box-sizing: border-box;
		background-color: #f0f0f0;
		overflow-y: scroll;
		float: left;

		.canshiInfo {
			width: 100%;

			.canshiItem {
				position: relative;
				width: 100%;
				height: 240rpx;
				background-color: #f0f0f0;
				margin-bottom: 45rpx;

				.countNumBox {
					display: flex;
					align-items: center;
					position: absolute;
					bottom: 30rpx;
					right: 30rpx;

					.add {
						display: flex;
						justify-content: center;
						height: 40rpx;
						line-height: 40rpx;
						font-size: 40rpx;
						width: 40rpx;
						border-radius: 50%;
						border: 1rpx solid #121212;
					}

					.reduce {
						display: flex;
						justify-content: center;
						height: 40rpx;
						line-height: 40rpx;
						font-size: 40rpx;
						width: 40rpx;
						border-radius: 50%;
						border: 1rpx solid #121212;
					}

					.countNum {
						width: 50rpx;
						text-align: center;
						font-size: 30rpx;
						margin-left: 10rpx;
						margin-right: 10rpx
					}
				}

				.canshiAdd {
					position: absolute;
					width: 50rpx;
					height: 50rpx;
					bottom: 30rpx;
					right: 30rpx;
				}

				.new {
					position: absolute;
					width: 54rpx;
					height: 56rpx;
					top: 0rpx;
					right: 0rpx;
				}

				.canshiPriceBox {
					position: absolute;
					top: 95rpx;
					left: 300rpx;
					display: flex;
					align-items: center;

					.linePrice {
						color: #8e8e8e;
						font-weight: 500;
						font-size: 22rpx;
						margin-left: 20rpx;
						text-decoration: line-through;
					}

					.sellPrice {
						color: #121212;
						font-weight: 700;
						font-size: 30rpx;
					}
				}

				.canshiName {
					position: absolute;
					font-weight: 700;
					font-size: 28rpx;
					color: #121212;
					top: 25rpx;
					left: 300rpx;
					width: 200rpx;
				}

				.canshiPoster {
					width: 264rpx;
					height: 212rpx;
					margin-top: 14rpx;
					margin-left: 14rpx;
				}
			}
		}
	}

	.leftMenuBox {
		float: left;
		width: 160rpx;
		height: 65vh;
		padding-top: 45rpx;
		padding-bottom: 45rpx;
		box-sizing: border-box;
		overflow-y: scroll;

		.leftMenuItem {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			margin-bottom: 80rpx;
			font-size: 26rpx;
			height: 26rpx;
		}

		.leftMenuItemActive {
			font-weight: 700;
		}

		.leftLine {
			position: absolute;
			width: 4rpx;
			height: 100%;
			left: 0;
			top: 0;
			background-color: #ff7565;
		}
	}

	.topMenuBox {
		width: 100%;
		height: 130rpx;
		display: flex;
		border-bottom: 1rpx solid #d0d0d0;

		.topMenuItem {
			width: 25%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			font-size: 26rpx;
		}

		.triangle {
			position: absolute;
			bottom: 0;
			width: 0;
			height: 0;
			border-top: 12rpx solid transparent;
			border-right: 12rpx solid transparent;
			border-left: 12rpx solid transparent;
			border-bottom: 12rpx solid #000000;

		}

		.topMenuItemActive {
			font-weight: 700;
			border-bottom: 1rpx solid #000000;
		}
	}

	.swiperBox {
		width: 100%;
		height: 250rpx;

		.swiperItem {
			width: 100%;
			height: 100%;
		}
	}

	.container {
		width: 100%;
		height: 100vh;
	}
</style>